package com.example.rbac.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class ApiTestClient {

    public static void main(String[] args) {
        try {
            // 测试用户注册接口
            String registerUrl = "http://localhost:8080/auth/register";
            String registerBody = "{\"username\":\"testadmin\",\"password\":\"testadmin123\",\"nickname\":\"测试管理员\"}";
            System.out.println("Testing register API...");
            String registerResponse = sendPostRequest(registerUrl, registerBody);
            System.out.println("Register Response: " + registerResponse);
            
            // 测试用户登录接口
            String loginUrl = "http://localhost:8080/auth/login";
            String loginBody = "{\"username\":\"testadmin\",\"password\":\"testadmin123\"}";
            System.out.println("\nTesting login API...");
            String loginResponse = sendPostRequest(loginUrl, loginBody);
            System.out.println("Login Response: " + loginResponse);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String sendPostRequest(String urlString, String requestBody) throws Exception {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setDoOutput(true);
        
        // 发送请求体
        try (OutputStream os = conn.getOutputStream()) {
            byte[] input = requestBody.getBytes("utf-8");
            os.write(input, 0, input.length);
        }
        
        // 读取响应
        StringBuilder response = new StringBuilder();
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(conn.getInputStream(), "utf-8"))) {
            String responseLine = null;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine.trim());
            }
        } catch (Exception e) {
            // 读取错误响应
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(conn.getErrorStream(), "utf-8"))) {
                String responseLine = null;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
            }
            System.out.println("HTTP Error Code: " + conn.getResponseCode());
        }
        
        return response.toString();
    }
}